//
//  LiveTableViewController.m
//  LiveSoftware
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "LiveTableViewController.h"

@interface LiveTableViewController () <UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>

@property(nonatomic,strong) NSMutableArray *channelArray;
@property(nonatomic,strong) UIWebView *liveWebView;
@property(nonatomic,strong) LiveScoreModel *scoreModel;

@end


@implementation LiveTableViewController



- (void)requestData
{
    // 图片

    NSString *homeTeamLogo = [@"%2f" stringByAppendingString:self.model.home_logo];
    self.homeLogoUrl = [NSString stringWithFormat:@"http://duihui.oss-cn-hangzhou.aliyuncs.com/zuqiu%@.png",homeTeamLogo];
    NSString *visitTeamLogo = [@"%2f" stringByAppendingString:self.model.visit_logo];
    self.visitLogoUrl = [NSString stringWithFormat:@"http://duihui.oss-cn-hangzhou.aliyuncs.com/zuqiu%@.png",visitTeamLogo];
    
    
    
    NSString *url = [NSString stringWithFormat:@"http://m.zhibo8.cc/m/android/json%@.json?aabbccddeeff=%@",self.urlLast,self.currentTime];
//    NSLog(@"url===============%@",url);
//    NSLog(@"%@",_currentTime);
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *superDict = (NSDictionary *)response;
        NSArray *channel = [superDict valueForKey:@"channel"];
        self.channelArray = [NSMutableArray array];
        for (NSMutableDictionary *smallDict in channel) {
            LiveSignalModel *model = [LiveSignalModel liveSignalModelWithDict:smallDict];
            NSString *str = [model.name substringToIndex:1];
            if (!([str isEqualToString:@"比"] || [str isEqualToString:@"D"] || [str isEqualToString:@"更"] || [str isEqualToString:@"体"] || [str isEqualToString:@"互"])) {
                [self.channelArray addObject:model];
            }
//            NSLog(@"channelArray%lu",self.channelArray.count);
        }
        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络错误");
    }];
    // 比分赋值
        NSString *scoreUrl = [NSString stringWithFormat:@"http://m.zhibo8.cc/json/bifen%@.json?aabbccddeeff=%@",self.urlLast,self.currentTime];
//    NSLog(@"比分直播======%@",scoreUrl);
        [LORequestManger GET:scoreUrl success:^(id response) {
            NSDictionary *dict = (NSDictionary *)response;
            self.scoreModel = [LiveScoreModel liveScoreModelWithDict:dict];
            NSLog(@"%@",self.scoreModel);
            // 请求数据后再次赋值
                [self setHeaderView2];
                [self.tableView reloadData];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"网络错误");
        }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
//    [self setHeaderView];

    NSLog(@"self.isSelected==============%d",self.isSelected);
    [self setHeaderView2];
    [self customNavigationBar];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self pullDownToRefresh];

}

#pragma mark - 下拉刷新
- (void)pullDownToRefresh
{
    __unsafe_unretained typeof(self) vc = self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [vc requestData];
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [vc.tableView.header endRefreshing];
            [vc.tableView reloadData];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.channelArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cell";
    [tableView registerClass:[LiveSingnalTableViewCell class] forCellReuseIdentifier:cellID];
    LiveSingnalTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:cellID ];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row == (self.channelArray.count)) {
        cell.signalLabel.text = @"比分直播";
    }
    else
    {
        LiveSignalModel *model = self.channelArray[indexPath.row];
        cell.signalLabel.text = model.name;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == (self.channelArray.count))
    {
        
        // 跳到指定的tabBarController
//           self.tabBarController.selectedIndex = 2;
        
        self.tabBarController.selectedViewController = self.tabBarController.viewControllers[2];
        
        
        
        [ (ScoreViewController*)[self.tabBarController.viewControllers[2] topViewController] addTimes];


        
#warning 2.0版新功能
//        if (self.selected ==NO)
//        {
//            
//            [ (ScoreViewController*)[self.tabBarController.viewControllers[2] topViewController] addTimes];
//            
//            
//            [ (ScoreViewController*)[self.tabBarController.viewControllers[2] topViewController]  leftButton:nil ];
//        }
////        //跳转到篮球
//        else
//        {
//            [ (ScoreViewController*)[self.tabBarController.viewControllers[2] topViewController]  rightButton:nil ];
//            
//                 
//                 
//        }
//        

        
        
    }
    else
    {
        LiveSignalModel *model = self.channelArray[indexPath.row];
        PlayViewController *playVC = [[PlayViewController alloc] init];
        playVC.playUrl = model.url;
        self.navigationController.navigationBarHidden = NO;
        [self.navigationController pushViewController:playVC animated:YES];
    }
}








- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kScreenIp6(90);
}

#pragma mark - 自定义导航栏
- (void)customNavigationBar
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"header_bg_green_2@2x"] forBarMetrics:UIBarMetricsDefault];
    
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"set_arrow_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popback)];
    [backBarButton setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBarButton;
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenIp6(50), kScreenIp6(30))];
    title.text = self.model.matchProperty;
    title.textColor = [UIColor whiteColor];
    [self.navigationItem setTitleView:title];
}

- (void)popback
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 自定义HeaderView
- (void)setHeaderView
{
    CGFloat gap = kScreenIp6(20);
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , kScreenIp6(60) + 4 * gap)];
    
    CGFloat labelW = (kScreenWidth - 2 *gap) / 3;
    CGFloat labelH = kScreenIp6(60);
    UILabel *homeTeam = [[UILabel alloc] initWithFrame:CGRectMake(gap, gap, labelW, labelH)];
    //    homeTeam.adjustsFontSizeToFitWidth = YES;
    homeTeam.textAlignment = 1;
    homeTeam.font = [UIFont systemFontOfSize:15];
    [headerView addSubview:homeTeam];
    
    CGFloat timeLabelX = CGRectGetMaxX(homeTeam.frame);
    CGFloat timeLabelH = labelH / 3 * 2;
    UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(timeLabelX, gap, labelW, timeLabelH)];
    timeLabel.textAlignment = 1;
    [headerView addSubview:timeLabel];
    
    CGFloat dateLabelY = CGRectGetMaxY(timeLabel.frame);
    CGFloat dateLabelH = labelH / 3;
    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(timeLabelX, dateLabelY, labelW, dateLabelH)];
    dateLabel.textAlignment = 1;
    dateLabel.font = [UIFont systemFontOfSize:12];
    dateLabel.textColor = [UIColor grayColor];
    [headerView addSubview:dateLabel];
    
    CGFloat visitTeamX = CGRectGetMaxX(timeLabel.frame);
    UILabel *visitTeam = [[UILabel alloc] initWithFrame:CGRectMake(visitTeamX, gap, labelW, labelH)];
    //    visitTeam.adjustsFontSizeToFitWidth = YES;
    visitTeam.textAlignment = 1;
    visitTeam.font = [UIFont systemFontOfSize:15];
    [headerView addSubview:visitTeam];
    
    CGFloat lineImageViewY = CGRectGetMaxY(dateLabel.frame) + kScreenIp6(30);
    UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(gap / 2, lineImageViewY, kScreenWidth - gap, 1)];
    lineImageView.image = [UIImage imageNamed:@"scanline"];
    [headerView addSubview:lineImageView];
    
    if (self.model.timeInterval < 0) {
        if (self.scoreModel) { // 比分直播网络正常
            // 比赛正在进行中的赋值
            NSString *score = [NSString stringWithFormat:@"%@ : %@",self.scoreModel.bifen_a,self.scoreModel.bifen_b];
            homeTeam.text = self.scoreModel.team_a;
            visitTeam.text = self.scoreModel.team_b;
            timeLabel.text = score;
            dateLabel.text = self.scoreModel.status;
        }
        else // 比分直播网络错误
        {
            homeTeam.text = self.model.home_team;
            visitTeam.text = self.model.visit_team;
            dateLabel.text = @"进行中";
            timeLabel.text = @" : ";
        }
    }
    else
    {
        // 比赛开始前赋值
        homeTeam.text = self.model.home_team;
        visitTeam.text = self.model.visit_team;
        dateLabel.text = self.model.sdate;
        timeLabel.text = self.model.time;
        
    }
    self.tableView.tableHeaderView = headerView;
}

- (void)setHeaderView2
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenIp6(140))];
    
    LiveSingnalHeaderView *headView = [[LiveSingnalHeaderView alloc] initWithFrame:CGRectMake(kScreenIp6(40), kScreenIp6(20), kScreenWidth - kScreenIp6(40)*2, kScreenIp6(60))];
    
    if (self.model.timeInterval < 0) {
        if (self.scoreModel) { // 比分直播网络正常
            // 比赛正在进行中的赋值
            NSString *score = [NSString stringWithFormat:@"%@ : %@",self.scoreModel.bifen_a,self.scoreModel.bifen_b];
            headView.score.text = score;
            headView.dateLabel.text = @"进行中";
            headView.hostName.text = self.scoreModel.team_a;
            headView.guestName.text = self.scoreModel.team_b;
            [headView.hostLogo setImageWithURL:[NSURL URLWithString:self.homeLogoUrl] placeholderImage:[UIImage imageNamed:@"zhudui_1"]];
            [headView.guestLogo setImageWithURL:[NSURL URLWithString:self.visitLogoUrl] placeholderImage:[UIImage imageNamed:@"kedui_2"]];

        }
        else // 比分直播网络错误
        {
            
            headView.score.text = @" : ";
            headView.dateLabel.text = @"进行中";
            headView.hostName.text = self.model.home_team;
            headView.guestName.text = self.model.visit_team;
            [headView.hostLogo setImageWithURL:[NSURL URLWithString:self.homeLogoUrl] placeholderImage:[UIImage imageNamed:@"zhudui_1"]];
            [headView.guestLogo setImageWithURL:[NSURL URLWithString:self.visitLogoUrl] placeholderImage:[UIImage imageNamed:@"kedui_2"]];

        }
    }
    else
    {
        // 比赛开始前赋值
        headView.score.text = self.model.time;
        headView.hostName.text = self.model.home_team;
        headView.guestName.text = self.model.visit_team;
        [headView.hostLogo setImageWithURL:[NSURL URLWithString:self.homeLogoUrl] placeholderImage:[UIImage imageNamed:@"zhudui_1"]];
        [headView.guestLogo setImageWithURL:[NSURL URLWithString:self.visitLogoUrl] placeholderImage:[UIImage imageNamed:@"kedui_2"]];
        headView.dateLabel.text = self.model.sdate;

    }
    
    [headerView addSubview:headView];
    
    self.tableView.tableHeaderView = headerView;

}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return kScreenIp6(140);
//}


// 设置分区表头的方案
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    return [self setSectionHeaderView];
//}

- (UIView *)setSectionHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenIp6(140))];
    
    LiveSingnalHeaderView *headView = [[LiveSingnalHeaderView alloc] initWithFrame:CGRectMake(kScreenIp6(40), kScreenIp6(20), kScreenWidth - kScreenIp6(40)*2, kScreenIp6(60))];
    
    if (self.model.timeInterval < 0) {
        if (self.scoreModel) { // 比分直播网络正常
            // 比赛正在进行中的赋值
            NSString *score = [NSString stringWithFormat:@"%@ : %@",self.scoreModel.bifen_a,self.scoreModel.bifen_b];
            headView.score.text = score;
            headView.dateLabel.text = @"进行中";
            headView.hostName.text = self.scoreModel.team_a;
            headView.guestName.text = self.scoreModel.team_b;
            [headView.hostLogo setImageWithURL:[NSURL URLWithString:self.homeLogoUrl] placeholderImage:[UIImage imageNamed:@"zhudui_1"]];
            [headView.guestLogo setImageWithURL:[NSURL URLWithString:self.visitLogoUrl] placeholderImage:[UIImage imageNamed:@"kedui_2"]];
            
        }
        else // 比分直播网络错误
        {
            
            headView.score.text = self.model.time;
            headView.dateLabel.text = @"进行中";
            headView.hostName.text = self.model.home_team;
            headView.guestName.text = self.model.visit_team;
            [headView.hostLogo setImageWithURL:[NSURL URLWithString:self.homeLogoUrl] placeholderImage:[UIImage imageNamed:@"zhudui_1"]];
            [headView.guestLogo setImageWithURL:[NSURL URLWithString:self.visitLogoUrl] placeholderImage:[UIImage imageNamed:@"kedui_2"]];
            headView.dateLabel.text = self.model.sdate;
            
        }
    }
    else
    {
        // 比赛开始前赋值
        headView.score.text = self.model.time;
        headView.hostName.text = self.model.home_team;
        headView.guestName.text = self.model.visit_team;
        [headView.hostLogo setImageWithURL:[NSURL URLWithString:self.homeLogoUrl] placeholderImage:[UIImage imageNamed:@"zhudui_1"]];
        [headView.guestLogo setImageWithURL:[NSURL URLWithString:self.visitLogoUrl] placeholderImage:[UIImage imageNamed:@"kedui_2"]];
        headView.dateLabel.text = self.model.sdate;
        
    }
    
    [headerView addSubview:headView];
    

    headerView.backgroundColor = [UIColor darkGrayColor];
    return headerView;
}

#pragma mark - 隐藏和显示导航栏
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}



@end
